package kassiopeia.gui

import kassiopeia.commons.AgentStatus;
import kassiopeia.commons.io.Ping;
import kassiopeia.commons.model.task.TaskDescriptor;
import kassiopeia.commons.model.xml.TaskDescriptorXmlSerializer;
import kassiopeia.gui.task.Task;

class DistributionController {

    TaskDatabaseService taskDatabaseService
    TaskSenderService taskSenderService
    AgentService agentService

    def index = {
        [tasks:taskDatabaseService.getAllTasks(), pings:agentService.getAllPings()]
    }

    def submitTask = {
        def message = validateTaskSubmission(params)
        if(message) {
            flash.message = message
            redirect(action:index)
            return
        }

        Task task = taskDatabaseService.getTaskByName(params.taskName)
        TaskDescriptor descriptor = TaskConverter.convert(task)

        taskSenderService.sendTask(descriptor,params.list('agentId'))

        flash.message = "Task submitted"
        redirect(action:index)
    }

    def validateTaskSubmission(params) {
        if(!taskDatabaseService.getTaskByName(params.taskName)) {
            return "Invalid or missing task name"
        }

        if(!params.agentId) {
            return "Please, select at least one agent"
        }

        def pings = agentService.getAllPings()
        def aliveAgentIds = []
        for(ping in pings) {
            aliveAgentIds.add(ping.sourceId)
        }

        for(agentId in params.list('agentId')) {
            if(!(agentId in aliveAgentIds)) {
                return "Invalid agent identifier: " + agentId
            }
        }
        return null
    }
}
